package tgc.edu.exam.controller;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.HashSet;
import java.util.List;

import javax.persistence.criteria.CriteriaBuilder;
import javax.persistence.criteria.CriteriaQuery;
import javax.persistence.criteria.Predicate;
import javax.persistence.criteria.Root;

import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.Pageable;
import org.springframework.data.domain.Sort;
import org.springframework.data.domain.Sort.Direction;
import org.springframework.data.jpa.domain.Specification;
import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;
import org.springframework.stereotype.Controller;
import org.springframework.ui.ModelMap;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

import tgc.edu.exam.custom.DataGridParam;
import tgc.edu.exam.custom.DataGridUtils;
import tgc.edu.exam.entity.Log;
import tgc.edu.exam.entity.Permission;
import tgc.edu.exam.entity.SysRole;
import tgc.edu.exam.entity.SysUser;
import tgc.edu.exam.entity.User;
import tgc.edu.exam.form.UserForm;
import tgc.edu.exam.security.UserUtils;
import tgc.edu.exam.service.LogService;
import tgc.edu.exam.service.SysRoleService;
import tgc.edu.exam.service.SysUserService;
import tgc.edu.exam.service.UserService;

@Controller
@RequestMapping("/user")
public class UserController {

	@Autowired
	private UserService userService;
	@Autowired
	private SysRoleService roleService;
	@Autowired
	private SysUserService sysuserService;
	@Autowired
	private UserUtils userUtils;
	@Autowired
	private LogService logService;
	
	@RequestMapping("/jwd")
	@ResponseBody
	public void jwd(double jwd) {
		System.out.println(jwd+"======");
	}
	
	@RequestMapping("/manage")
	public String manage() {
		return "user/manage";
	}
	@RequestMapping("/page")
	@ResponseBody
	public Object page(UserForm form,DataGridParam param) {
		Pageable pageable = param.getPageable();
		Specification<User> spec = buildSpec(form);
		Page<User> page = userService.findAll(spec,pageable);
		HashMap<String, Object> result = DataGridUtils.buildResult(page);
		return result;
	}
	
	private Specification<User> buildSpec(UserForm form) {
		Specification<User> spec = new Specification<User>() {
			private static final long serialVersionUID = 1L;
			@Override
			public Predicate toPredicate(Root<User> root, CriteriaQuery<?> query, CriteriaBuilder cb) {
				HashSet<Predicate> rules = new HashSet<>();
				String name = form.getName();
				String username = form.getUsername();
				if (StringUtils.hasText(name)) {
					rules.add(cb.like(root.get("name"), "%"+name+"%"));
				}else if (StringUtils.hasText(username)) {
					rules.add(cb.like(root.get("username"), "%"+username+"%"));
				}
				return cb.and(rules.toArray(new Predicate[rules.size()]));
			}
		};
		return spec;
	}
	/**
	 * 编辑
	 * @param form
	 * @param map
	 * @return
	 */
	@RequestMapping("/edit")
	public Object edit(UserForm form,ModelMap map) {
		User model = new User();
		if(form.getId()!=null) {
			model = userService.findById(form.getId());
		}
		map.put("model", model);
		List<SysRole> roles = roleService.findByParentIsNull();
		map.put("roles", roles);
		return "user/edit";
	}
	/**
	 * 保存用户
	 * @param form
	 * @return
	 */
	@RequestMapping("/save")
	@ResponseBody
	public Object save(UserForm form) {
		User user = new User();
		Integer id = form.getId();
		if(id!=null) {
			user = userService.findById(id);
			BeanUtils.copyProperties(form, user,"password");
		}else {
			BCryptPasswordEncoder encoder = new BCryptPasswordEncoder();
			form.setPassword(encoder.encode("123456"));
			BeanUtils.copyProperties(form, user);
		}
		String role = form.getRole();
		List<SysRole> roles = new ArrayList<>();
		roles.add(roleService.findByCode(role));
		user.setRole(roles);
		userService.save(user);
		return "保存成功";
		
	}
	/**
	 * 删除用户
	 * @param id
	 * @return
	 */
	@RequestMapping("/delete")
	@ResponseBody
	public String delete(Integer id) {
		userService.deleteById(id);
		return "已删除";
	}
	/**
	 * 重置密码
	 * @param id
	 * @return
	 */
	@RequestMapping("/refresh")
	@ResponseBody
	public String refresh(Integer id) {
		SysUser model = sysuserService.findById(id);
		BCryptPasswordEncoder encoder = new BCryptPasswordEncoder();
		model.setPassword(encoder.encode("123456"));
		sysuserService.save(model);
		return "重置成功";
	}

	/**
	 * 个人信息
	 * @return
	 */
	@RequestMapping("/information")
	public String information() {
		return "personal/information";
		
	}
	/**
	 * 修改个人信息
	 */
	@RequestMapping("/changeInfo")
	@ResponseBody
	public void changeInfo(UserForm form) {
		SysUser user = userUtils.getUser();
		User model = userService.findById(user.getId());
		model.setName(form.getName());
		model.setPhone(form.getPhone());
		model.setSex(form.getSex());
		model.setAge(form.getAge());
		userService.save(model);
	}
	/**
	 * 操作日志
	 * @return
	 */
	@RequestMapping("/managelog")
	public String managelog() {
		return "personal/managelog";
		
	}
	@RequestMapping("/logpage")
	@ResponseBody
	public Object logpage(DataGridParam param,Log log) {
		Sort sort = new Sort(Direction.DESC,"id");
		Pageable pageable = param.getPageable(sort);
		Specification<Log> spec = buildSpecLog(log);
		Page<Log> page = logService.findAll(spec,pageable);
		return DataGridUtils.buildResult(page);
		
	}
	private Specification<Log> buildSpecLog(Log log) {
		return null;
	} 
}
